<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useMessage } from 'naive-ui'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'

interface Todo {
  id: string
  content: string
  completed: boolean
  priority: 'high' | 'medium' | 'low'
  createdAt: number
  completedAt?: number
  updatedAt?: number
}

type Priority = 'high' | 'medium' | 'low'
type PriorityGroups = Record<Priority, Todo[]>

const message = useMessage()
const todos = ref<Todo[]>([])
const newTodoContent = ref('')
const selectedPriority = ref<'high' | 'medium' | 'low'>('medium')
const sortBy = ref<'priority' | 'time' | 'completed'>('priority')
const editingTodo = ref<Todo | null>(null)
const editContent = ref('')
const showCompleted = ref(true)

// 优先级配置
const priorities = {
  high: {
    label: '高优先级',
    color: 'text-red-500 dark:text-red-400',
    bgColor: 'bg-red-50 dark:bg-red-900/20',
    borderColor: 'border-red-200 dark:border-red-800',
    order: 1
  },
  medium: {
    label: '中优先级',
    color: 'text-yellow-500 dark:text-yellow-400',
    bgColor: 'bg-yellow-50 dark:bg-yellow-900/20',
    borderColor: 'border-yellow-200 dark:border-yellow-800',
    order: 2
  },
  low: {
    label: '低优先级',
    color: 'text-blue-500 dark:text-blue-400',
    bgColor: 'bg-blue-50 dark:bg-blue-900/20',
    borderColor: 'border-blue-200 dark:border-blue-800',
    order: 3
  }
}

const priorityList = computed<Priority[]>(() => ['high', 'medium', 'low'])

// 从 localStorage 加载数据
const loadTodos = () => {
  const savedTodos = localStorage.getItem('todos')
  if (savedTodos) {
    todos.value = JSON.parse(savedTodos)
  }
}

// 保存到 localStorage
const saveTodos = () => {
  localStorage.setItem('todos', JSON.stringify(todos.value))
}

// 添加新待办事项
const addTodo = () => {
  if (!newTodoContent.value.trim()) {
    message.warning('请输入待办事项内容')
    return
  }

  const todo: Todo = {
    id: Date.now().toString(),
    content: newTodoContent.value.trim(),
    completed: false,
    priority: selectedPriority.value,
    createdAt: Date.now()
  }

  todos.value.unshift(todo)
  saveTodos()
  newTodoContent.value = ''
  message.success('待办事项已添加')
}

// 切换待办事项状态
const toggleTodo = (todo: Todo) => {
  todo.completed = !todo.completed
  todo.completedAt = todo.completed ? Date.now() : undefined
  saveTodos()
  message.success(todo.completed ? '已完成' : '已取消完成')
}

// 删除待办事项
const deleteTodo = (todo: Todo) => {
  if (confirm('确定要删除这个待办事项吗？')) {
    todos.value = todos.value.filter(t => t.id !== todo.id)
    saveTodos()
    message.success('待办事项已删除')
  }
}

// 格式化时间
const formatTime = (timestamp: number) => {
  return format(timestamp, 'yyyy年MM月dd日 HH:mm:ss', { locale: zhCN })
}

// 编辑待办事项
const startEdit = (todo: Todo) => {
  editingTodo.value = todo
  editContent.value = todo.content
}

const saveEdit = () => {
  if (!editContent.value.trim()) {
    message.warning('内容不能为空')
    return
  }

  if (editingTodo.value) {
    const index = todos.value.findIndex(t => t.id === editingTodo.value!.id)
    if (index !== -1) {
      todos.value[index] = {
        ...editingTodo.value,
        content: editContent.value.trim(),
        updatedAt: Date.now()
      }
      saveTodos()
      message.success('更新成功')
    }
  }
  editingTodo.value = null
}

const cancelEdit = () => {
  editingTodo.value = null
}

// 按优先级分组的待办事项
const groupedTodos = computed(() => {
  const filtered = todos.value.filter(todo => showCompleted.value || !todo.completed)
  const groups: PriorityGroups = {
    high: filtered.filter(todo => todo.priority === 'high'),
    medium: filtered.filter(todo => todo.priority === 'medium'),
    low: filtered.filter(todo => todo.priority === 'low')
  }
  
  if (sortBy.value === 'time') {
    Object.values(groups).forEach(group => {
      group.sort((a, b) => b.createdAt - a.createdAt)
    })
  } else if (sortBy.value === 'completed') {
    Object.values(groups).forEach(group => {
      group.sort((a, b) => (a.completed === b.completed ? 0 : a.completed ? 1 : -1))
    })
  }
  
  return groups
})

onMounted(() => {
  loadTodos()
})
</script>

<template>
  <div class="max-w-4xl mx-auto p-4">
    <n-card>
      <template #header>
        <div class="text-2xl font-bold">待办事项</div>
        <p class="mt-2 text-gray-600 dark:text-gray-400 text-sm">
          支持优先级管理的待办事项清单
        </p>
      </template>

      <n-space vertical size="large">
        <!-- 添加待办事项表单 -->
        <div class="flex gap-2">
          <n-input
            v-model:value="newTodoContent"
            type="text"
            placeholder="输入新的待办事项..."
            @keyup.enter="addTodo"
          />
          <n-select
            v-model:value="selectedPriority"
            :options="[
              { label: '高优先级', value: 'high' },
              { label: '中优先级', value: 'medium' },
              { label: '低优先级', value: 'low' }
            ]"
            class="w-32"
          />
          <n-button type="primary" @click="addTodo">
            添加
          </n-button>
        </div>

        <!-- 工具栏 -->
        <div class="flex items-center justify-between">
          <n-radio-group v-model:value="sortBy" size="small">
            <n-radio-button value="priority">
              优先级
            </n-radio-button>
            <n-radio-button value="time">
              时间
            </n-radio-button>
            <n-radio-button value="completed">
              完成状态
            </n-radio-button>
          </n-radio-group>

          <n-switch v-model:value="showCompleted">
            <template #checked>显示已完成</template>
            <template #unchecked>隐藏已完成</template>
          </n-switch>
        </div>

        <!-- 待办事项列表（按优先级分组） -->
        <div class="space-y-6">
          <template v-if="todos.length">
            <div v-for="priority in priorityList" :key="priority" class="space-y-2">
              <h3 v-if="groupedTodos[priority].length" :class="[
                'font-medium mb-2',
                priorities[priority].color
              ]">
                {{ priorities[priority].label }}
                ({{ groupedTodos[priority].length }})
              </h3>
              
              <div v-for="todo in groupedTodos[priority]" :key="todo.id" 
                :class="[
                  'p-4 rounded-lg border transition-all',
                  priorities[todo.priority].bgColor,
                  priorities[todo.priority].borderColor,
                  todo.completed ? 'opacity-60' : ''
                ]"
              >
                <div class="flex items-start gap-4">
                  <!-- 复选框 -->
                  <n-checkbox
                    :checked="todo.completed"
                    @update:checked="toggleTodo(todo)"
                  />

                  <div class="flex-1 min-w-0">
                    <!-- 内容 -->
                    <div v-if="editingTodo?.id !== todo.id">
                      <div :class="[
                        'text-gray-900 dark:text-gray-100',
                        todo.completed ? 'line-through' : ''
                      ]">
                        {{ todo.content }}
                      </div>
                    </div>
                    <div v-else class="flex gap-2">
                      <n-input
                        v-model:value="editContent"
                        type="text"
                        @keyup.enter="saveEdit"
                      />
                      <n-button size="small" type="primary" @click="saveEdit">
                        保存
                      </n-button>
                      <n-button size="small" @click="cancelEdit">
                        取消
                      </n-button>
                    </div>

                    <!-- 元信息 -->
                    <div class="mt-1 text-xs space-y-1">
                      <div class="text-gray-500">
                        创建于: {{ formatTime(todo.createdAt) }}
                      </div>
                      <div v-if="todo.completed && todo.completedAt" class="text-gray-500">
                        完成于: {{ formatTime(todo.completedAt) }}
                      </div>
                    </div>
                  </div>

                  <!-- 操作按钮 -->
                  <div class="flex gap-2">
                    <n-button
                      v-if="editingTodo?.id !== todo.id"
                      tertiary
                      size="small"
                      @click="startEdit(todo)"
                    >
                      编辑
                    </n-button>
                    <n-button
                      tertiary
                      type="error"
                      size="small"
                      @click="deleteTodo(todo)"
                    >
                      删除
                    </n-button>
                  </div>
                </div>
              </div>
            </div>
          </template>
          <div v-else class="text-center text-gray-500 py-8">
            暂无待办事项
          </div>
        </div>
      </n-space>
    </n-card>
  </div>
</template>

<style scoped>
.n-checkbox {
  margin-top: 3px;
}
</style> 